(function() {

	// 常量
	var constant = {
		IS_INIT : 'isInit',
		IS_NOREASON : 'noReason',
		NOREASON_ICON : $.utils.noData.icons,
		SERVER : jsContextPath || '',
		PARAM_SUFFIX : 'lsS',
		ICON_MAP : {
			'table' : 'table',
			'chart1' : 'column',
			'chart2' : 'pie',
			'chart3' : 'line',
			'chart4' : 'area',
			'chart5' : 'bubble',
			'chart6' : 'radar'
		}
	};

	/**
	 * item构造函数
	 */
	Item = function(option) {

		var defaultOpt = $.extend(true, {
			/**
			 * items示例： 'Z-R005-003-2':{ init:funName, lazy:true }, key:模块ID，
			 * value: init：初始化函数名； lazy：是否延迟加载，true:是，false:否； parent:父模块编号；
			 * beforeHandler:前处理函数，在初始化前执行的函数； afterHandler：后处理函数,
			 * link:“更多”按钮的url, formObj:{}
			 */
			items : {},
			postData : null,
			formId : 'queryForm',// form元素ID
			paramHandler : paramHandler
		}, option || {});

		this.option = defaultOpt;
	};

	/**
	 * 创建item
	 */
	Item.prototype.create = function() {

		var items = this.option.items;
		for ( var code in items) {
			var opt = items[code];
			var element = $('#' + code);

			// 缓存option
			element[0].itemConf = opt;

			if (!opt.lazy) {
				// 切换tab页
				var parent = $('#' + opt.parent);
				var tabs = parent.find('ul.tab-header li a');
				this.activeTab(tabs);

				itemHandler.call(this, element, opt);
			}

		}
	};

	/**
	 * 刷新item
	 */
	Item.prototype.refresh = function(config) {

		var option = this.option, items = option.items;

		var paramHandler = option.paramHandler;

		var params = paramHandler($('#' + option.formId), option.postData);

		for ( var code in items) {
			var item = $('#' + code);
			var itemOpt = items[code];
			var parent = $('#' + itemOpt.parent);
			var tabs = parent.find('ul.tab-header');

			// 刷新图表
			if (tabs.length == 0 || !item.is(':hidden')) {
				updateChartnGrid(item, params);
			} else {// tab页
				var tabParent = item.parents('.tab-content');

				if (tabParent.is(':hidden')) {
					item.attr(constant.IS_INIT, '0');
				} else {
					updateChartnGrid(item, params);
				}
			}
		}
	};

	/**
	 * 切换tab页
	 */
	Item.prototype.activeTab = function(tabs) {

		var items = this;
		var option = items.option;

		tabs.click(function() {
			var arr = this.href.split('#');
			var href = arr.pop();
			var tab = $('#' + href);
			var item = tab.find('.chart');

			if (item.length == 0) {
				item = tab.find('.grid');
			}

			if (item.length > 0) {
				var itemConf = item[0].itemConf;
				var isInit = item.attr(constant.IS_INIT);
				if (!isInit || '0' === isInit) {
					// 是否已经初始化过
				if (item.children().length > 0) {

					item.attr(constant.IS_INIT, '1');

					var params = option.paramHandler(option.formId,
							option.postData);
					updateChartnGrid(item, params);
				} else {
					itemHandler.call(items, item, itemConf);
				}
			}
		}
	})	;
	};

	function itemHandler(element, itemOpt) {

		var div = this;
		var option = this.option || {};
		var params = option.paramHandler($('#' + option.formId),
				option.postData);

		var postData = {};
		postData['MODULE_CODE'] = itemOpt.parent;
		var beforeHandler = itemOpt.beforeHandler || itemBeforeHandler;
		var afterHandler = itemOpt.afterHandler;

		$
				.ajax( {
					url : jsContextPath + '/module/getModules.do',
					type : 'post',
					data : postData,
					dataType : 'json',
					success : function(data, stauts, XHR) {
						var paraMap = getFormData(element, params);
						var module = data.module || {};

						var pmodules = module.pmodules || [], modules = module.modules
								|| [];

						var pmodule = pmodules.length > 0 ? pmodules[0] : {};

						var pData = modules.length > 0 ? modules[0] : {};

						if (modules.length > 1) {
							var parentEl = element.parents('.tab-content'), pId = parentEl
									.attr('id');
							for ( var i in modules) {
								if (pId == modules[i]['MODULE_CODE']) {
									pData = modules[i];
									break;
								}
							}
						}

						// var parent = $('#' + itemOpt.parent);
						var parent = element.parents('.kit-col');
						var header = parent.find('h2 i');
						var iconMap = constant.ICON_MAP;
						var icon;

						for ( var k in iconMap) {
							if (header.hasClass('kit-icon-' + k)) {
								icon = k;
								break;
							}
						}
						//解决多tab页情况下，不执行图形init方法时，不同报表不同icon问题
						if(itemOpt.icon != undefined){
							icon = itemOpt.icon;
						}
						
						if ($.isFunction(beforeHandler)) {
							itemOpt.reasonIcon = constant.NOREASON_ICON[itemOpt.reasonIcon
									|| constant.ICON_MAP[icon]];
							beforeHandler(element, itemOpt, modules, pmodule);
						}

						var isBo = pData['IS_BO'];
						var modulePage = pData['MODULE_PAGE'];

						if ((isBo && '1' == isBo) || modulePage) {

							var url = pData['URL'];
							url = modulePage ? constant.SERVER + '/' + url
									: url;
							var pageConf = {
								parmSuffix : modulePage ? ''
										: constant.PARAM_SUFFIX,
								url : url
							};

							// 缓存URL
							element[0].pageConf = pageConf;

							pageHandler(element, paraMap, true, pageConf);
						} else {
							var init = itemOpt.init;
							// 初始化图表
							if ($.isFunction(init)) {

								var nodata = {
									icon : constant.ICON_MAP[icon]
								};
								// scope是图表元素，传form参数和nodata
								init.call(element, paraMap, nodata);
							}
						}

						element.attr(constant.IS_INIT, '1');
						link.call(div, parent, itemOpt);
						if ($.isFunction(afterHandler)) {
							afterHandler(element, itemOpt, modules, pmodule);
						}
					}
				});
	}
	;

	/**
	 * URL处理函数
	 */
	function pageHandler(el, params, newPage, pageConf) {

		var url = pageConf.url, parmSuffix = pageConf.parmSuffix;

		if (url) {
			// 添加loading
			$.utils.loading.show(el);

			var ifrm;
			if (newPage) {// 新建iframe
				ifrm = $('<iframe width="100%" frameborder="0"  scrolling="no"></iframe>');
				el.append(ifrm);
				ifrm.css( {
					'height' : el.parent().height()
				});
			} else {
				ifrm = el.find('iframe');
			}

			ifrm.hide();

			url = concatUrl(url);
			var str = param2Str(params, parmSuffix);

			window.setTimeout(function() {
				// 移除loading
					$.utils.loading.hide(el);
					ifrm.show();
					ifrm.attr('src', url + str);
				}, 1000);

		}

	}
	;

	function param2Str(params, parmSuffix) {
		var str = '';
		for ( var k in params) {
			if (k && params[k]) {
				var v = params[k];
				var reg=/[\u0391-\uFFE5]/;
		        if(reg.test(v)){    
		            v = encodeURIComponent(params[k])
		        }   
				str += '&' + parmSuffix + k + '=' + v;
			}
		}
		str = str.replace(/^&/, '');
		return str;
	}
	;

	function concatUrl(url) {

		var qs = '?';
		if (url.indexOf(qs) > -1) {
			url += '&';
		} else {
			url += qs;
		}

		return url;
	}
	;

	/**
	 * 默认的前处理
	 */
	function itemBeforeHandler(el, itemOpt, modules, pmodule) {

		var parent = $('#' + itemOpt.parent);
		var content = parent.find('div.panel-content');

		if ('0' == pmodule['STATUS']) {
			// 保留下拉框条件吧
			// var divs = content.children();
			// content = $(divs).last();
			buildReason(content, content, pmodule, itemOpt);
			return;
		}

		// tab子菜单显示原因
		var tabItems = content.find('.tab-content');

		for ( var i = 0; i < tabItems.length; i++) {
			var tabItem = $(tabItems[i]);

			if (!tabItem.is(':hidden')) {
				var id = tabItem.attr('id');
				for ( var j in modules) {
					var module = modules[j];

					if (id == module['MODULE_CODE'] && '0' == module['STATUS']) {
						content = el.parent();
						tabItem.find('div.panel-bar').hide();
						buildReason(content, content, module, itemOpt);
						break;
					}
				}
			}

		}
	}
	;

	/**
	 * 默认的参数处理函数
	 */
	function paramHandler(form, postData) {

		var postData_ = $.utils.getFormData($(form).attr('id'));

		postData = $.extend(postData || {}, postData_);

		return postData;
	}
	;

	function getFormData(element, params) {
		var paraMap = $.extend(true, {}, params);
		var panel = element.parents('.panel-content');
		var forms = panel.find('form');

		for ( var i = 0; i < forms.length; i++) {
			var form = $(forms[i]);
			if ('none' != form.css('display')) {
				var paraArr = form.find('*[name]');
				for ( var j = 0; j < paraArr.length; j++) {
					var a = $(paraArr[j]);
					var selOpt = a[0].selOpt;
					if (selOpt) {
						var defLabel = selOpt.defLabel;
						if (defLabel.enable) {
							paraMap[a.attr('name')] = defLabel.code;
						}
					} else {
						paraMap[a.attr('name')] = a.val();
					}
				}
			}
		}

		return paraMap;
	}
	;

	/**
	 * 创建原因DIV
	 */
	function buildReason(el, moduleEl, data, itemOpt) {

		var icon = itemOpt.reasonIcon;
		// var moduleParent = moduleEl.parent();
		el.empty();

		// 先清除元素内的子元素
		// el.empty();
		el.attr(constant.IS_NOREASON, '1');
		buildReasonDiv(moduleEl, data, icon);
	}
	;

	/**
	 * 更新图表
	 */
	function updateChartnGrid(element, params) {

		var elDom = element[0] ? element[0] : {};
		var itemConf = elDom.itemConf || {};
		var pageConf = elDom.pageConf;

		var paraMap = getFormData(element, params);

		if (pageConf) {
			pageHandler(element, paraMap, false, pageConf);
			return;
		}

		if (element.hasClass('chart')) {
			element.updateChart( {
				params : paraMap
			});
		} else if (element.hasClass('grid')) {

			element.jqGrid('setGridConfig', {
				paramObj : paraMap
			});
			element.doFind();
		}
	}
	;

	// 合并object对象
	function objMerge(source, target) {
		var result = $(true, source || {}, target || {});
		return result;
	}
	;

	function link(div, itemOpt) {
		var el = this;
		var more = div.find('.button-more');

		if (more.length > 0) {

			var isInit = more.attr(constant.IS_INIT);

			if ('1' == isInit) {
				return;
			}

			more[0].linkOpt = {
				url : itemOpt.link,
				el : el,
				parent : div
			};

			more.attr(constant.IS_INIT, '1');
			more
					.click(function() {
						var linkOpt = this.linkOpt || {};
						var url = linkOpt.url, el = linkOpt.el, parent = linkOpt.parent;

						if (url.indexOf('jsp') != -1) {
							url = constant.SERVER + '/' + url;
						}

						var option = el.option;
						var paramHandler = option.paramHandler;
						var params = paramHandler($('#' + option.formId));
						params = $.extend( {}, paraMap, params);
						var forms = parent.find('form');

						for ( var i = 0; i < forms.length; i++) {
							var form = $(forms[i]);
							if (!form.is(':hidden')) {
								params = $.extend(params, paramHandler(form));
							}
						}

						var str = param2Str(params, '');
						url = concatUrl(url);

						window.open(url + str);
					});
		}

	}
	;

})();

function buildReasonDiv(el, data, icon) {
	var nodataBox = $('<div class="nodataBox"></div>');

	var nodata = $('<div class="nodata">' + '<i class="' + icon
			+ '-nodata icon-nodata"></i>' + '<div class="nodata-info">'
			+ '<p>当前业务系统数据暂时无法支持，<br />等待业务系统功能固化中......'
			+ '<br />点击<a href="javascript:;" class="js-reason-btn">查看原因</a>'
			+ '</p>' + '</div>' + '</div>');
	nodataBox.append(nodata);

	var reason = $('<div class="reason"></div>');
	nodata.append(reason);

	var tabRow1 = $('<div class="table-row"></div>');
	var title1 = $('<div class="table-col-1"></div>');
	var reasonText1 = $('<div class="table-col-11 reason-text"></div>');

	var tabRow2 = tabRow1.clone(true), tabRow3 = tabRow1.clone(true);
	var title2 = title1.clone(true), title3 = title1.clone(true);
	var reasonText2 = reasonText1.clone(true), reasonText3 = reasonText1
			.clone(true);

	tabRow1.append(title1);
	title1.append('需求:');
	title1.addClass('reason-demand');
	tabRow1.append(reasonText1);
	reasonText1.append(data['REQUIREMENT']);

	tabRow2.append(title2);
	title2.append('问题:');
	title2.addClass('reason-question');
	tabRow2.append(reasonText2);
	reasonText2.append(data['REASON']);

	tabRow3.append(title3);
	title3.append('建议:');
	title3.addClass('reason-suggest');
	tabRow3.append(reasonText3);
	reasonText3.append(data['ADVICE']);

	reason.append(tabRow1);
	reason.append(tabRow2);
	reason.append(tabRow3);

	el.append(nodataBox);
};